package com.example.bookseckill.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.example.bookseckill.entity.Books;
import com.example.bookseckill.entity.SeckillBook;
import com.example.bookseckill.entity.Users;
import com.example.bookseckill.entity.to.SeckillSkuRedisTo;
import com.example.bookseckill.entity.to.mq.SeckillOrderTo;
import com.example.bookseckill.feign.BooksService;
import com.example.bookseckill.interceptor.LoginUserInterceptor;
import com.example.bookseckill.service.SeckillService;
import com.example.bookseckill.service.SeckillSessionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Resource
    private BooksService booksService;
    @Resource
    private SeckillSessionService seckillSessionService;
    @Resource
    private RedissonClient redissonClient;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //
    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    private final String SECKILL_CHARE_PREFIX = "seckill:skus";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";    //+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //1.扫描最近3天要参加的秒杀活动
        List<SeckillBook> lates3DayBook = seckillSessionService.getLates3DaySession();
        if (lates3DayBook != null && lates3DayBook.size() >0){
            //上架
            //缓存到redis
            //1.缓存活动信息
            saveSessionInfos(lates3DayBook);

            //2、缓存活动的关联商品信息
            saveSessionSkuInfo(lates3DayBook);

        }
    }

    /**
     * 获取到当前可以参加秒杀商品的信息
     * @return
     */
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1.确定当前属于哪个秒杀场次
        long currentTime = System.currentTimeMillis();
        //从Redis中查询到所有的key，以seckill:sessions开头的所有数据
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        List<SeckillSkuRedisTo> collect =new ArrayList<>();
        for (String key : keys) {
            //seckill:sessions:1721864679000_1721922284000
            String replace = key.replace(SESSION_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            //获取存入Redis商品的开始时间
            long startTime = Long.parseLong(s[0]);
            //结束时间
            long endTime = Long.parseLong(s[1]);
            //判断是否是当前秒杀场次
            if (currentTime >= startTime && currentTime <= endTime){
                //2.获取这个秒杀场次需要的所有商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
                assert range != null;
                List<String> listValue = hashOps.multiGet(range);
                if (listValue != null && listValue.size() >= 0){
                    for (String items : listValue) {
                        collect.add(JSON.parseObject(items, SeckillSkuRedisTo.class));
                    }
                }
            }
        }
        return collect;
    }

    /**
     * 当前商品进行秒杀
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) throws InterruptedException {
        long s1 = System.currentTimeMillis();
        //获取当前用户的信息
//        Users user = LoginUserInterceptor.loginUser.get();
        Users user = new Users();
        user.setUserId(2L);
        //1.获取当前秒杀商品的详细信息从Redis中获取
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
        String skuInfoValue  = hashOps.get(killId);
        if (StringUtils.isEmpty(skuInfoValue)){
            return null;
        }
        //(合法性校验)
        SeckillSkuRedisTo redisTo = JSON.parseObject(skuInfoValue, SeckillSkuRedisTo.class);
        Long startTime = redisTo.getStartTime();
        Long endTime = redisTo.getEndTime();
        long currentTime = System.currentTimeMillis();
        //判断当前这个秒杀请求是否在活动时间区间内（校验时间的合法性）
        if (currentTime >= startTime && currentTime <= endTime){

            //2.校验随机码和商品id
            String randomCode = redisTo.getRandomCode();
            String skuId = redisTo.getPromotionSessionId() + "-" + redisTo.getSkuId();
            if (randomCode.equals(key) && killId.equals(skuId)){
                //3.验证购物数量是否合理和库存是否充足
                Integer seckillLimit = redisTo.getSeckillLimit();

                //获取信息量
                String seckillCount = redisTemplate.opsForValue().get(SKU_STOCK_SEMAPHORE + randomCode);
                Integer count = Integer.valueOf(seckillCount);
                //判断信号量是否大于0,并且买的数量不能超过库存
                if (count > 0 && num <= seckillLimit && count > num){
                    //4.验证这个人是否已经买过了（幂等性处理），如果秒杀成功，就去占位。
                    String redisKey = user.getUserId() + "-" + skuId;
                    //设置自动过期（活动结束时间 - 当前时间）
                    long ttl = endTime - currentTime;
                    Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                    if (aBoolean){
                        //占位成功说明从来没有买过，分布式锁（获取信号量-1）
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                        //TODO 秒杀成功，快速下单
                        boolean semaphoreCount  = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                        //保证Redis中还有商品库存
                        if (semaphoreCount){
                            //创建订单号和订单信息发送给MQ
                            //秒杀成功，快速下单 发送消息到 MQ 整个操作时间在 10 ms 左右
                            String timeId = IdWorker.getTimeId();
                            SeckillOrderTo orderTo = new SeckillOrderTo();
                            orderTo.setOrderSn(timeId);
//                            orderTo.setMemberId(user.getId());
                            orderTo.setNum(num);
                            orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                            orderTo.setSkuId(redisTo.getSkuId());
//                            orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                            rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
                            long s2 = System.currentTimeMillis();
                            log.info("耗时..." + (s2 - s1));
                            return timeId;
                        }
                    }
                }
            }
        }
        long s3 = System.currentTimeMillis();
        log.info("耗时..." + (s3 - s1));
        return null;
    }

    /**
     * 缓存秒杀活动信息
     * @param lates3DayBook
     */
    private void saveSessionInfos(List<SeckillBook> lates3DayBook){
        if (!CollectionUtils.isEmpty(lates3DayBook)){
            lates3DayBook.stream().forEach(books -> {
                long startTime = books.getStartTime().getTime();
                long endTime = books.getEndTime().getTime();

                //定义存到Redis中的key
                String key =  SESSION_CACHE_PREFIX + startTime + "_" + endTime;

                //判断Redis中是否有该信息，如果没有才进行添加
                Boolean hasKey = redisTemplate.hasKey(key);
                //缓存活动信息
                if (!hasKey){
                    //获取到活动中所有商品的skuId
                    List<String> skuIds =books.getRelationSkus().stream()
                            .map(item -> item.getPromotionSessionId()+ "-" + item.getSkuId().toString()).collect(Collectors.toList() );
                    //将活动场次的id和单个书的id组合存入redis中
                    redisTemplate.opsForList().leftPushAll(key,skuIds);
                }
            } );
        }
    }
    /**
     * 缓存秒杀活动所关联的商品信息
     * @param sessions
     */
    private void saveSessionSkuInfo(List<SeckillBook> lates3DayBook){
        if (!CollectionUtils.isEmpty(lates3DayBook)){
            lates3DayBook.stream().forEach( books -> {
                //准备hash操作，绑定hash
                BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(SECKILL_CHARE_PREFIX);
                books.getRelationSkus().stream().forEach(seckillSkuVo -> {
                    //生成随机码
                    String token = UUID.randomUUID().toString().replace("-", "");

                    String redisKey = seckillSkuVo.getPromotionSessionId().toString() + "-" + seckillSkuVo.getSkuId().toString();
                    if (!operations.hasKey(redisKey)){
                        //缓存商品信息
                        SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                        Long skuId = seckillSkuVo.getSkuId();
                        //1.先查询sku的基本信息，调用远程
                        Books book = booksService.getSukId(skuId);
                        if (book != null){
                            redisTo.setSkuInfo(book);
                        }

                        //2.sku的秒杀信息
                        BeanUtils.copyProperties(seckillSkuVo,redisTo);

                        //3.设置当前商品的秒杀时间信息
                        redisTo.setStartTime(books.getStartTime().getTime());
                        redisTo.setEndTime(books.getEndTime().getTime());

                        //4.设置商品的随机码（防止恶意攻击）
                        redisTo.setRandomCode(token);

                        //序列化json格式存入Redis中
                        String seckillValue = JSON.toJSONString(redisTo);
                        System.out.println("单个商品"+seckillValue);
                        System.out.println("h活动场次"+seckillSkuVo.getPromotionSessionId().toString() +seckillSkuVo.getSkuId().toString() );
                        operations.put(redisKey,seckillValue);

                        //如果当前这个场次的商品库存信息已经上架就不需要上架
                        //5.使用库存作为分布式Redisson信号量（限流）
                        //使用库存作为分布式信号量
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                        //商品可以秒杀的数量作为信号量
                        semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                    }
                });
            });
        }
    }
}
